﻿from pymongo import Connection

class Period(object):
	def __init__(self, **data):
		self.__dict__.update(data)
	
	@classmethod
	def new(cls, periodID, observations=[]):
		return cls(**{'periodID':periodID, 'observations':observations})
	
class Observation(object):
	def __init__(self, **data):
		self.__dict__.update(data)
	
	@classmethod
	def new(cls, date, temp, windSpeed, windDirection):
		data = {'date':date, 'temperature':temp, 'windSpeed':windSpeed, 'windDirection':windDirection }
		return cls(**data)
	
class Repository:
	def __init__(self):
		connection = Connection()
		db = connection.weatherDB
		self.periods = db.periods
	
	def findPeriods(self, criteria={}):
		lst = list()
			
		for period in self.periods.find(criteria):
			observations = [Observation(**observation) for observation in period['observations']]
			lst.append(Period.new(period['periodID'], observations))
			
		return lst
	
	def add(self, observation):
		date = observation.date
		self.periods.update({"periodID":"%s%02d%02d" %(date.year, date.month, date.day)}, {"$addToSet":{"observations":observation.__dict__}}, safe=True, upsert=True)			
	
